<template>
    <div class="row rowlist">
        <div @click="show = !show" class="col cu" :style="{ height: '50px', lineHeight: '50px', fontWeight: 600 }">
            {{ row.name }}
        </div>
        <div @click="show = !show" :style="{ width: '120px', height: '50px', lineHeight: '50px' }"
            class="text-center cu">
            {{ rowtype[row.type || 'question'] }}
        </div>
        <div @click="show = !show" :style="{ width: '120px', height: '50px', lineHeight: '50px' }"
            class="text-center cu">
            {{ dayjs(row.starttime).format('YYYY-MM-DD') }}
        </div>
        <div @click="show = !show" :style="{ width: '120px', height: '50px', lineHeight: '50px' }"
            class="text-center cu">
            {{ dayjs(row.endtime).format('YYYY-MM-DD') }}
        </div>
        <div @click="show = !show" :style="{ width: '120px', height: '50px', lineHeight: '50px' }"
            class="text-center cu">
            {{ times(row) }}
        </div>
        <div @click="show = !show" :style="{ width: '120px', height: '50px', lineHeight: '50px' }"
            class="text-center cu">
            {{ row.usercount }} 人
        </div>
        <div :style="{ width: '270px', height: '50px', lineHeight: '50px' }">
            <router-link v-if="data?.ID" v-slot="{ navigate }" custom :to="{
            name: '创建工作',
            params: { ID: data?.ID },
            query: {
                ID: row.ID
            }
        }">
                <el-button @click="navigate" v-show="isAdmin" size="default">修改</el-button>
            </router-link>
            <el-button @click="del(row.ID)" v-show="isAdmin" size="default">删除</el-button>
            <el-button @click="click(row.ID)" size="default">
                完成名单
            </el-button>

        </div>
        <div :style="{ width: '40px', lineHeight: '50px' }" class="text-center">
            <el-icon class="cu">
                <arrow-right v-show="!show" @click="show = !show" />
                <arrow-down v-show="show" @click="show = !show" />
            </el-icon>
        </div>
        <br>
        <el-collapse-transition>
            <div v-show="show" class="rowitem">
                <div class="rowitemdiv">
                    <p v-show="row.description">任务描述：{{ row.description }}</p>
                    <p v-if="row.type === 'question'">任务完成条件：完成{{ row.questionnum }}题, 且代码题目测试点正确率{{ row.questionac }}%
                    </p>
                    <p v-else-if="row.type === 'video'">任务完成条件：观看{{ row.questionnum }}节课程视频, 且观看视频时长大于{{ row.questionac
                        }}%
                    </p>
                    <p v-else-if="row.type === 'file'">任务完成条件：学习{{ row.questionnum }}份资料</p>
                    <hr>
                    <p v-if="userjob.isshow" class="row">
                    <div :style="{ width: '120px' }">我的进度：</div>
                    <div :style="{ width: '300px', padding: '5px' }">
                        <el-progress :percentage="userjob.num" />
                    </div>
                    </p>
                    <p v-show="row.reward">任务奖励：{{ row.reward }}</p>
                    <p v-show="row.remarks">备注：{{ row.remarks }}</p>
                    <div class="button111">
                        <el-button :disabled="disabled.disabled"
                            v-show="disabled.show ? tabledata.length && (row.isall || userjob.isshow) : false"
                            :loading="loading" size="default" @click="myclick" type="primary">{{
            disabled.message
        }}
                        </el-button>
                    </div>
                </div>
            </div>
        </el-collapse-transition>
        <el-dialog v-model="dialogVisible2" :title="row ? row.name : '没有找到'" width="700px">
            <template #header>
                <div class="container-fluid" :style="{
            backgroundColor: 'var(--color-43)',
            color: '#fff',
            margin: '-20px',
            width: '700px',
            padding: '24px'
        }">
                    <div class="row">
                        <div class="col" :style="{ fontSize: '18px' }">
                            {{ row ? row.name : '没有找到' }}
                        </div>
                    </div>
                    <div class="row">
                        <div class="col">
                            任务完成条件：完成{{ row.questionnum }}题, 且代码题目测试点正确率{{ row.questionac }}%
                        </div>
                    </div>
                </div>
            </template>
            <div class="container-fluid">
                <div class="row cu"
                    :style="{ borderBottom: '1px solid #434343', height: '48px', color: 'var(--color-43)', lineHeight: '48px', fontWeight: 700 }">
                    <div :style="{ width: '80px' }">题目ID</div>
                    <div class="col">题目名称</div>
                    <div class="col text-center">标签</div>
                    <div :style="{ width: '80px' }">我的进度</div>
                </div>
                <router-link v-for="(v, key) in tabledata" :key="key" :to="{
            name: '题目',
            params: { ID: v.ID },
            query: { jobid: v.teamjobid }
        }" custom v-slot="{ navigate, href }">
                    <el-link :href="href" :underline="false" target="_blank" class="row cu-list">
                        <div :style="{ width: '80px' }">
                            {{ v?.ID }}
                        </div>
                        <div class="col">
                            {{ v?.name }}
                        </div>
                        <div class="col text-center">
                            <button class="btn btn-outline-dark btn-sm" v-for="(vo, keys) in v.questionlabel"
                                v-text="getlabel.find(e => e.ID === vo.labelid)?.name" :key="`1-${keys}`"></button>
                        </div>
                        <div :style="{ width: '80px' }" class="text-center">
                            <el-icon>
                                <circle-check-filled color="#67C23A" v-show="v.state" />
                                <warning-filled color="#F56C6C" v-show="!v.state" />
                            </el-icon>
                        </div>
                    </el-link>
                </router-link>
            </div>
        </el-dialog>
        <el-dialog v-model="dialogVisible3" :title="row ? row.name : '没有找到'" width="700px">
            <template #header>
                <div class="container-fluid" :style="{
            backgroundColor: 'var(--color-43)',
            color: '#fff',
            margin: '-20px',
            width: '700px',
            padding: '24px'
        }">
                    <div class="row">
                        <div class="col" :style="{ fontSize: '18px' }">
                            {{ row ? row.name : '没有找到' }}
                        </div>
                    </div>
                    <div class="row">
                        <div class="col">
                            任务完成条件：观看{{ row.questionnum }}节课程课程, 且观看时长超过{{ row.questionac }}%
                        </div>
                    </div>
                </div>
            </template>
            <div class="container-fluid">
                <div class="row cu"
                    :style="{ borderBottom: '1px solid #434343', height: '48px', color: 'var(--color-43)', lineHeight: '48px', fontWeight: 700 }">
                    <div :style="{ width: '80px' }">课程ID</div>
                    <div class="col">课程名称</div>
                    <div :style="{ width: '80px' }">我的进度</div>
                </div>
                <el-link v-for="(v, key) in tabledata" :key="key"
                    :href="`https://www.hterobot.com/home.html#/course/${v?.ID}?lession=0&catebag=${v.catebagid}`"
                    :underline="false" target="_blank" class="row cu-list">
                    <div :style="{ width: '80px' }">
                        {{ v?.ID }}
                    </div>
                    <div class=" col">
                        {{ v?.name }}
                    </div>
                    <div :style="{ width: '80px' }" class="text-center">
                        <el-icon>
                            <circle-check-filled color="#67C23A" v-show="v.state" />
                            <warning-filled color="#F56C6C" v-show="!v.state" />
                        </el-icon>
                    </div>
                </el-link>
            </div>
        </el-dialog>
        <el-dialog v-model="dialogVisible4" :title="row ? row.name : '没有找到'" width="700px">
            <template #header>
                <div class="container-fluid" :style="{
            backgroundColor: 'var(--color-43)',
            color: '#fff',
            margin: '-20px',
            width: '700px',
            padding: '24px'
        }">
                    <div class="row">
                        <div class="col" :style="{ fontSize: '18px' }">
                            {{ row ? row.name : '没有找到' }}
                        </div>
                    </div>
                    <div class="row">
                        <div class="col">
                            任务完成条件：学习{{ row.questionnum }}份资料
                        </div>
                    </div>
                </div>
            </template>
            <div class="container-fluid">
                <div class="row cu"
                    :style="{ borderBottom: '1px solid #434343', height: '48px', color: 'var(--color-43)', lineHeight: '48px', fontWeight: 700 }">
                    <div :style="{ width: '80px' }">文件ID</div>
                    <div class="col">文件名称</div>
                    <div :style="{ width: '80px' }">我的进度</div>
                </div>
                <div v-for="(v, key) in tabledata" :underline="false" target="_blank" @click="download(v)"
                    class="row cu-list cu">
                    <div :style="{ width: '80px' }">
                        {{ v?.ID }}
                    </div>
                    <div class=" col">
                        {{ v?.name }}
                    </div>
                    <div :style="{ width: '80px' }" class="text-center">
                        <el-icon>
                            <circle-check-filled color="#67C23A" v-show="v.state" />
                            <warning-filled color="#F56C6C" v-show="!v.state" />
                        </el-icon>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ArrowDown, ArrowRight, CircleCheckFilled, WarningFilled } from '@element-plus/icons-vue';
import OSS from 'ali-oss';
import dayjs from 'dayjs';
import { ElMessage } from 'element-plus';
import { uniq } from 'lodash-es';
import { groupBy, mapObject } from 'underscore';
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { asynccreatedteamjobrelation, asyncupdateteamflow, ossupload } from '../../../api';
import { Storekey } from '../../../interface';
import Studycodemodel from '../../../mysql_interface/studycodemodel';
const rowtype: Record<"question" | "video" | "file", string> = {
    video: '观看视频',
    question: '题目练习',
    file: '学习资料'
}

const p = defineProps<{ row: Studycodemodel.Iteamjob, isAdmin: Studycodemodel.Iteamuser['isAdmin'], click: (ID?: number) => void, del: (ID?: number) => void, data: Studycodemodel.Iteam, user: Studycodemodel.Iuser, _tabledata: { ID?: number, name?: string, }[], start: () => void, useflow: any, flow: any, setflow: any }>()
const store = useStore(Storekey)
const getlabel = computed(() => {
    return store.state.label?.rows || []
})
const router = useRouter()
const show = ref(false)
const tabledata = computed(() => {
    const data = p.row.teamjobrelation?.filter(e => e.userid === p.user.ID).map(n => {

        if (p.row.type === 'question') {
            const e = p._tabledata.find(z => z.ID === n.questionid)
            const index = p.row.jobquestion?.find(z => n.questionid === z.questionid)?.index || 0
            return {
                ...e,
                state: n.state,
                catebagid: n.catebagid,
                index,
                teamjobid: p.row.ID
            }
        } else if (p.row.type === 'video') {
            const e = p._tabledata.find(z => z.ID === n.courseid)
            const index = p.row.jobquestion?.find(z => n.courseid === z.questionid)?.index || 0
            return {
                ...e,
                state: n.state,
                catebagid: n.catebagid,
                index,
                teamjobid: p.row.ID
            }
        } else if (p.row.type === 'file') {
            const e = p._tabledata.find(z => z.ID === n.teamfileid)
            const index = p.row.jobquestion?.find(z => n.teamfileid === z.teamfileid)?.index || 0
            return {
                ...e,
                state: n.state,
                teamfileid: n.teamfileid,
                index,
                teamjobid: p.row.ID
            }
        }
        return {
            name: '',
            state: false,
            ID: 0,
            questionlabel: [],
            index: 0,
            teamjobid: p.row.ID
        }
    }).sort((a, b) => a.index - b.index)
    return data || []

})

onMounted(() => {
    show.value = times(p.row) === '进行中'
})

const disabled = computed(() => {
    const n = dayjs().unix()
    if (n < dayjs(p.row.starttime).unix()) {
        return {
            disabled: true,
            message: '任务没有开始',
            show: true
        }
    }
    if (n > dayjs(p.row.endtime).unix()) {
        return {
            disabled: true,
            message: '任务已经结束',
            show: false

        }
    }
    return {
        disabled: false,
        message: '去完成',
        show: true

    }
})

const loading = ref(false)
async function myclick() {
    loading.value = true
    if (p.row.type === 'question') {
        const questionid = uniq(p.row.teamjobrelation?.map(e => e.questionid))
        let id = p.row.teamjobrelation?.filter(f => f.userid === p.user.ID).map(e => e.questionid)
        if (!id?.length) {
            await asynccreatedteamjobrelation({
                teamid: Number(p.data.ID),
                list: questionid.map(e => {
                    return {
                        questionid: e,
                        userid: store.state.user?.ID,
                        state: false,
                        teamjobid: p.row.ID
                    }
                })
            })
            await p.start()
        }
        dialogVisible2.value = true
    } else if (p.row.type === 'video') {
        dialogVisible3.value = true
    } else if (p.row.type === 'file') {
        const res = await ossupload()
        o.value = new OSS({
            region: "oss-cn-qingdao",
            accessKeyId: res.accessKeyId,
            accessKeySecret: res.accessKeySecret,
            stsToken: res.securityToken,
            bucket: 'ojteam',
            refreshSTSToken: async () => {
                const info = await ossupload();
                return {
                    accessKeyId: info.accessKeyId,
                    accessKeySecret: info.accessKeySecret,
                    stsToken: info.securityToken
                }
            }

        })
        dialogVisible4.value = true
    }
    loading.value = false

}


const dialogVisible2 = ref(false)
const dialogVisible3 = ref(false)
const dialogVisible4 = ref(false)

const userjob = computed(() => {
    if (p.user) {
        const questionnum = p.row.questionnum || 1
        const n = p.row.teamjobrelation?.filter(e => e.userid === p.user.ID)
        if (n?.length) {
            const _n = n.filter(e => !e.state)
            const num = Math.floor(n.filter(e => e.state).length / questionnum * 100)
            return {
                isshow: true,
                num: num > 100 ? 100 : num,
                next: _n
            }
        }
    }
    return {
        isshow: false,
        num: 0
    }
})

function times(data: Studycodemodel.Iteamjob) {
    const { starttime, endtime } = data
    const n = dayjs().unix()
    if (n < dayjs(starttime).unix()) {
        return '未开始'
    }
    if (n > dayjs(endtime).unix()) {
        return '已结束'
    }
    return '进行中'
}

function useusers(data?: Studycodemodel.Iteamjobrelation[]) {
    if (data) {
        const gr = groupBy(data, e => e.userid || 0)
        const v = mapObject(gr, f => {
            const n = f.filter(e => e.state === true)
            return n.length
        })
        return Object.values(v).filter(e => e >= (p.row?.questionnum || 0)).length
    }
    return 0


}
const o = ref<OSS>()

async function download(name: Studycodemodel.Iteamfile) {
    if (p.useflow._useflow > p.useflow._flow) {
        ElMessage.error('本月团队资料流量已用完，如需帮助请联系助教老师或管理员')
        return
    }
    const data = o.value?.signatureUrl(String(name.url), {
        expires: 300
    })
    await asyncupdateteamflow({ ID: p.flow?.ID, useflow: p.flow?.useflow, size: name.size, teamid: p.data.ID, name: name.name, teamfileid: name.ID })
    window.open(data, '_blank')
    if (p.setflow) {
        p.setflow()
    }

}
</script>


<style scoped>
p {
    margin-bottom: 12px;
}

.button111 {
    position: absolute;
    bottom: 24px;
    right: 32px;
    width: 278px;
    text-align: center;
}

.cu-list {
    display: flex;
    height: 48px;
    color: var(--color-43);
    line-height: 48px;
    margin-top: 6px;
    background-color: #fff;
}

.cu-list:hover {
    background-color: var(--color-cheng);
    color: #fff;
}

.rowlist:hover {
    background-color: var(--color-f5);
}

.rowlist {
    background: #FAFAFA;
    /* Layer_line */

    border: 1px solid rgba(0, 0, 0, 0.06);
    border-radius: 3px;
    margin-bottom: 12px;
}

.rowlist div {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.rowitem {
    color: var(--color-ww);
    background-color: #fff;

}

.rowitemdiv {
    padding: 24px;
    min-height: 125px;
    position: relative;

}
</style>